package com.application.Activity;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ExpandableListView;
import android.widget.ListView;

import com.application.Adapter.MyConversationAdapter;
import com.application.Adapter.MyConversationAdapter.ViewConversation;
import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;


public class frmMyConversation extends ListActivity{

	//	ImageButton _btnmygroup;

	private static ArrayList<ViewConversation> _viewConverList = new ArrayList<MyConversationAdapter.ViewConversation>();
	private static ListView _listView;
	private static MyConversationAdapter _converAdapter;
	private static ExpandableListView expandListView;
	private static Context _cont ;
	//	private static MyConversationAdapter _converAdapter = new MyConversationAdapter(_cont,R.layout.listrow_listsubject, _viewConverList);
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.layout_comment_tree);


		_cont = this;
		//		_btnmygroup=(ImageButton)findViewById(R.id.conversation_btnmygroup);
		//_listView=(ListView) findViewById(R.id.conversation_lvlistgroup);
		expandListView=(ExpandableListView)findViewById(R.id.expandListComment);

		//_listView.setOnItemClickListener(onItemGroupClick);
		//		_btnmygroup.setOnClickListener(new OnClickListener() {
		//
		//			@Override
		//			public void onClick(View arg0) {
		//				Intent intent = new Intent(FrmConversation.this, FrmChatGroup.class);
		//				//truyen qua uẻnâme cua giao vien
		//				
		//				startActivity(intent);
		//			}
		//		});

		//setListAdapter();
	//	NetworkController.init_runnableUpdateMsgGroup();
		
		String[] pre={
				"Dwight D. Eisenhower",	"John F. Kennedy",	"Lyndon B. Johnson",	"Richard Nixon",	"Gerald Ford",	"Jimmy Carter","Ronald Reagan",	"George H. W. Bush",	"Bill Clinton",	"George W. Bush",	"Barack Obama"
		};
		
		setListAdapter(new ArrayAdapter<String>(this, R.layout.row_comment,pre));
	}


	/**
	 * xu ly khi click len 1 item cua list danh sach cac nhom
	 */
	OnItemClickListener onItemGroupClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
			// TODO Auto-generated method stub
			Intent intent;
			String path = ReadWriteFileController.DIRECTORY + "NeighborsList.xml";
			switch(_viewConverList.get(pos).get_type())
			{
			case 1: //chat peer
			{
//				Log.d("PEERDROID","Chat peer");
//				intent = new Intent(getBaseContext(), FrmChatPeer.class);
//				intent.putExtra("username", _viewConverList.get(pos).get_name());
//				intent.putExtra("IP", _viewConverList.get(pos).get_ip());
//				intent.putExtra("fullname",  _viewConverList.get(pos).get_fullName());
//				Log.d("PEERDROID","fullname: "+ _viewConverList.get(pos).get_fullName());
//
//				startActivity(intent);
//				break;
			}
			case 2://chat group
			{
//				Log.d("PEERDROID","chat invite conversation");
//				FrmChatInvite.set_usernameCreater(_viewConverList.get(pos).get_name());
//				ActivityController.getPeerActivity().startActivity(new Intent(ActivityController.getPeerActivity().getBaseContext(),FrmChatInvite.class));
//				break;
			}
			case 3:
			{
//				Log.d("PEERDROID","chat group conversation");
//				FrmChatGroup.set_usernameCreater(_viewConverList.get(pos).get_name());
//				ActivityController.getPeerActivity().startActivity(new Intent(ActivityController.getPeerActivity().getBaseContext(),FrmChatGroup.class));
//				break;
			}
			}

			//ActivityController.getPeerActivity().startActivity(new Intent(ActivityController.getPeerActivity().getBaseContext(),FrmDoTest.class));
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
		Log.d("PEERDROID", " vao on key down");
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			
			builder.setMessage("Bạn có chắc muốn thoát khỏi chương trình ?")
			.setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int id) {
					if(!NetworkController.isOffline())
					{
						String s = NetworkController.get_ipHost();
						NetworkController.SendMessageLogout();
//						NetworkController.peerRelease();
						//xoá danh sách hàng xóm khi thoát khỏi ứng dụng
//						ReadWriteFileController.deleteFile(ReadWriteFileController.pathNeighborsList);
						
					}
					//NetworkController.SendMessageLogout(new Address("192.168.173.20:5033"));
					Log.d("PEERDROID","Đã Thoát khỏi chương trình");
					finish();
//					System.exit(0);
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();
				}
			});
			AlertDialog alert = builder.create();
			alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255))); 
			alert.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);	
	}
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.d("PEERDROID","vao onstart conversation");
		ActivityController.setPeerActivity(this);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//		ShowSubjectList();	
		Log.d("PEERDROID", "vao resume");
		ActivityController.setPeerActivity(this);
	}
	public static void addViewConversation(ViewConversation v)
	{
		Log.d("PEERDROID", "addViewConversation");
		_viewConverList.add(v);
		updateAdapter();
		//		setListAdapter();
	}

	public static void receiveMessage(ArrayList<Object> mess)
	{
		Log.d("PEERDROID", "receiveMessage");
		//0:username <> 1: mess <> 2:type <> 3:ip <> 4:Fullname
		//kiểm tra mess mới hay cũ
		String name = mess.get(0).toString();
		String note = mess.get(1).toString();
		String fullName = mess.get(4).toString();
		int type = Integer.valueOf(mess.get(2).toString());
		String ip = null;
		if(mess.get(3) != null)
			ip= mess.get(3).toString();
		ViewConversation view = new ViewConversation(name, note, type, ip, fullName);
		//đã tồn tại --> update, chưa tồn tại thì add
		if(isExitInViewConversationList(view, type))
			updateViewConversationList(view);
		else
			addViewConversation(view);

	}


	/*hàm này set adapter cho list*/
	public static void setListAdapter()
	{
		
		
		// setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked,pre));
	//	expandListView.setAdapter(_converAdapter);
//		_converAdapter =new MyConversationAdapter(_cont,R.layout.listrow_listsubject, _viewConverList);
//		//_listView.setAdapter(_converAdapter);
//		ListAdapter adapList=new ListAdapter() {
//			
//			@Override
//			public void unregisterDataSetObserver(DataSetObserver observer) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//			@Override
//			public void registerDataSetObserver(DataSetObserver observer) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//			@Override
//			public boolean isEmpty() {
//				// TODO Auto-generated method stub
//				return false;
//			}
//			
//			@Override
//			public boolean hasStableIds() {
//				// TODO Auto-generated method stub
//				return false;
//			}
//			
//			@Override
//			public int getViewTypeCount() {
//				// TODO Auto-generated method stub
//				return 0;
//			}
//			
//			@Override
//			public View getView(int position, View convertView, ViewGroup parent) {
//				// TODO Auto-generated method stub
//				return null;
//			}
//			
//			@Override
//			public int getItemViewType(int position) {
//				// TODO Auto-generated method stub
//				return 0;
//			}
//			
//			@Override
//			public long getItemId(int position) {
//				// TODO Auto-generated method stub
//				return 0;
//			}
//			
//			@Override
//			public Object getItem(int position) {
//				// TODO Auto-generated method stub
//				return null;
//			}
//			
//			@Override
//			public int getCount() {
//				// TODO Auto-generated method stub
//				return 0;
//			}
//			
//			@Override
//			public boolean isEnabled(int position) {
//				// TODO Auto-generated method stub
//				return false;
//			}
//			
//			@Override
//			public boolean areAllItemsEnabled() {
//				// TODO Auto-generated method stub
//				return false;
//			}
//		};
		
	}

	/*hàm này update adapter cho list*/
	public static void updateAdapter()
	{
		Log.d("PEERDROID", "updateAdapter");
		_converAdapter.notifyDataSetInvalidated();
		_converAdapter.notifyDataSetChanged();
	}

	//hàm này update lại view conversation list
	public static void updateViewConversationList(ViewConversation view)
	{
		Log.d("PEERDROID", "updateViewConversationList");
		int index = getIndexViewConverList(view);
		if(index != -1)
		{
			if(_viewConverList.size() > index)
			{
				_viewConverList.remove(index);
				_viewConverList.add(view);
			}
		}
		updateAdapter();
		//		setListAdapter();
	}


	public static void deleteItemGroup(String keychat)
	{
		ViewConversation view = new ViewConversation();
		view.set_name(keychat);
		view.set_type(3);
		deleteViewConversationItem(view);
		updateAdapter();
	}
	public static void deleteItemInvite(String keychat)
	{
		ViewConversation view = new ViewConversation();
		view.set_name(keychat);
		view.set_type(2);
		deleteViewConversationItem(view);
		updateAdapter();
	}
	private static void deleteViewConversationItem(ViewConversation view)
	{
		int index = getIndexViewConverList(view);
		if(index != -1)
		{
			if(_viewConverList.size() > index)
			{
				_viewConverList.remove(index);
			}
		}
		updateAdapter();
	}

	private static int getIndexViewConverList(ViewConversation view)
	{
		int index = -1;
		int i = 0;
		for(ViewConversation v: _viewConverList)
		{
			if(view.get_type() == 1)
			{
				Log.d("PEERDROID", "vao getindex view converlist:");
				Log.d("PEERDROID", "view: " + view);
				Log.d("PEERDROID", "v: " + v);
				if(v.get_name().equals(view.get_name()) && v.get_ip().equals(view.get_ip()))
				{
					index = i;
					break;
				}
			}	
			else if(view.get_type() == 2)
			{
				if(v.get_name().equals(view.get_name()))
				{
					index = i;
					break;
				}
			}
			else if(view.get_type() == 3)
			{
				if(v.get_name().equals(view.get_name()))
				{
					index = i;
					break;
				}
			}
			i++;
		}
		return index;
	}

	private static boolean isExitInViewConversationList(ViewConversation view, int type)
	{
		for(ViewConversation v : _viewConverList)
		{
			switch(v.get_type())
			{
			case 1:
				if(v.get_name().equals(view.get_name()) && v.get_ip().equals(view.get_ip()))
					return true;
				break;
			case 2:
				if(v.get_name().equals(view.get_name()) && v.get_type() == view.get_type())
					return true;
				break;
			case 3:
				if(v.get_name().equals(view.get_name()) && v.get_type() == view.get_type())
					return true;
				break;
			}
		}
		return false;
	}

}
